<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useMapStore } from '@/stores/map'

defineProps({
  height: {
    type: Number,
    default: 0,
    required: true,
  },
})

const { setCurrentShop } = useMapStore()
const { mapGroundOverlayUrl, location, mapScale, mapShopList, isShowPopup, mapSightList } = storeToRefs(useMapStore())

const mapContext = ref(null)
const isReady = ref(false)

// 初始化地图层
async function onInitMapOverlay() {
  const instance = getCurrentInstance()
  mapContext.value = uni.createMapContext('map', instance)
  await mapContext.value.addGroundOverlay({
    id: 1,
    src: mapGroundOverlayUrl.value, // 手绘地图素材路径
    bounds: {
      southwest: location.value.southwest,
      northeast: location.value.northeast,
    },
  })
  await mapContext.value.addMarkers({
    markers: mapShopList.value.map(item => ({
      ...item,
      id: item.mapId,
    })),
  })
  await mapContext.value.addMarkers({
    markers: mapSightList.value.map(item => ({
      ...item,
      id: item.mapId,
    })),
  })
  isReady.value = true
}

function onMarkerTap(e) {
  const { detail: { markerId } } = e
  const shop = mapShopList.value.find(item => item.mapId === markerId)

  if (!shop) {
    const parking = mapSightList.value.find(item => item.mapId === markerId)
    setCurrentShop({
      ...parking,
      name: parking.title,
      type: 'parking',
    })
  }
  else {
    setCurrentShop(shop)
  }

  isShowPopup.value = true
}

function onRegionChange(e) {
  if (!isReady.value)
    return

  const { type, centerLocation } = e.detail
  if (type !== 'end')
    return

  const { latitude, longitude } = centerLocation
  const { southwest, northeast } = location.value
  let newLatitude = latitude
  let newLongitude = longitude

  // 检查是否超出设定范围
  if (latitude > northeast.latitude)
    newLatitude = northeast.latitude - 0.004
  if (latitude < southwest.latitude)
    newLatitude = southwest.latitude + 0.004
  if (longitude > northeast.longitude)
    newLongitude = northeast.longitude - 0.004
  if (longitude < southwest.longitude)
    newLongitude = southwest.longitude + 0.004

  // 如果超出范围，则使用 moveToLocation 方法重新设置中心点
  if (newLatitude !== latitude || newLongitude !== longitude) {
    mapContext.value.moveToLocation({
      latitude: newLatitude,
      longitude: newLongitude,
    })
  }
}

onMounted(() => {
  onInitMapOverlay()
})
</script>

<template>
  <view class="bg-gray-100 rounded-xl shadow center overflow-hidden">
    <map
      id="map"
      class="w-full"
      :style="{ height: `${height}px` }"
      :scale="mapScale.scale"
      :min-scale="15.5"
      :max-scale="18"
      :latitude="location.center.latitude"
      :longitude="location.center.longitude"
      :enable-poi="false"
      :show-location="true"
      @markertap="onMarkerTap"
      @regionchange="onRegionChange"
    />
  </view>
</template>
